<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace Svick\Console;

use Closure;
use Svick\File\File;
use Svick\Helper\Arr;
use Svick\Helper\Helper;

class Route
{
    /**
     * 创建路由缓存
     *
     * @return string
     */
    public function cache()
    {
        $routes_cache_path = Helper::path('cache::routes/');
        File::rmDirFiles($routes_cache_path);
        echo Console::colorGreen('Route cache cleared.') . PHP_EOL;
        File::mkDir($routes_cache_path);

        $routes_path = Helper::path('::routes/');
        if (!is_dir($routes_path)) {
            return '路由目录/routes不存在';
        }

        foreach (glob($routes_path . '*') as $route_file) {
            if (!is_file($route_file) || File::ext($route_file) != 'php') {
                continue;
            }
            require $route_file;

            $routes = \Svick\Route\Route::router()->getRoutes();
            $route_cache_file = $routes_cache_path . basename($route_file);

            $cache_content = "<?php \n\nreturn " . Arr::toPhpString($routes, 2) . ";\n";
            file_put_contents($route_cache_file, $cache_content);
        }

        return Console::colorGreen('Routes cached successfully.');
    }

    /**
     * 清除路由缓存
     *
     * @return void
     */
    public function clear()
    {
        $routes_cache_path = Helper::path('cache::routes/');
        File::rmDirFiles($routes_cache_path);
        echo Console::colorGreen('Route cache cleared.') . PHP_EOL;
    }
}
